<template>
  <!-- 联想搜索 -->
  <div class="search-suggest">
    <van-cell v-for="(item, index) in searchList" :key="index" :title="item" icon="search" @click="$emit('goSearch', item)">
      <div slot="title" v-html="higtlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { SearchSuggest } from '@/api/search'
// 导入 lodash 的防抖函数
import { debounce } from 'lodash'

export default {
  props: {
    searchVal: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      searchList: []
    }
  },
  created () {
    this.getSearchSuggest()
  },
  methods: {
    async getSearchSuggest (val) {
      try {
        const { data: res } = await SearchSuggest(val)
        console.log(res)
        this.searchList = res.data.options
      } catch (err) {
        this.$toast('数据获取失败，请重新获取')
      }
    },
    higtlight (text) {
      const higtlighter = `<span class="active">${this.searchVal}</span>`
      // 正则需要动态的参数  需要 new RegExp
      const reg = new RegExp(this.searchVal, 'gi')
      return text.replace(reg, higtlighter)
    }
  },
  watch: {
    searchVal: {
      // deounce 函数包裹要防抖处理的函数，第二个参数是防抖时间
      handler: debounce(function (val) {
        this.getSearchSuggest(val)
      }, 1000),
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggest {
  padding-top: 114px;
  /deep/ .active {
    color: rgb(215, 97, 116);
  }
}
</style>
